0

I have a command that extract a word from a file.

I want to rename that file using the word it extracted.

The command I use to extract the word, which I will use later to rename filename.txt, is the following:

$ grep -e "some words" -e "other words" filename.txt | awk '{print $1}' 

filename.txt content example:

dasdadas
asdasda
asdas
matched some words
asdas
asda

Expected result: filename.txt will be renamed to matched.txt.

Im kinda hoping this can be done using one-liner command.

This is won't work but maybe something like:

mv filename.txt $(grep -e "some words" -e "other words" filename.txt | awk '{print $1}').txt Note: Im certain that there will only be one match with thegrep`. Thanks.

  • The question, as asked, can't really be answered. Suppose the file has a line "some words" and another line "other words" - what would you expect the resulting filename to be? If "the first matching word is good enough" i.e. "some words" then the filename would end up "matched.txt" as you state. That said, I'll take a stab at a solution with the assumption the first match is good enough. – Stephan Dec 17 '16 at 3:53
  • im sure that there ill only be one match in filename.txt. I edited the post. thanks – unixnoob99 Dec 17 '16 at 3:56
  • With your recent edit, my answer should work. That said, I'll update the solution a bit so it won't matter if there is more than one match, it'll just take the first. – Stephan Dec 17 '16 at 3:57
1
#!/bin/bash 
old_file_name=$1  # take an argument for the file you want to muck with
new_file_name=$(grep -e "some words" -e "other words" "${old_file_name}" | awk '{print $1}' | head -n 1).txt 
mv "$old_file_name" "$new_file_name"
  • 1
    or almost all in one awk: awk '/some words/||/other words/ {print $1;exit}' $old_file_name – dave_thompson_085 Dec 17 '16 at 9:47
0

Using grep and awk in a single pipeline is rarely a good idea, since awk can do everything grep can:

awk '/(some|other) words/ {print $1}' filename.txt | xargs -I{} mv filename.txt {}.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.