I have a loop and I want to select some columns with awk and do sort, and then rename my output file with a new name. My awk and sort are working well, but I want to get a file name with a different name of my input file and I was not able to do it. I have different directories to run this loop: a, b and c. The command is:

for i in a b c 
    (cd $i/; for i in *_test2.txt; do awk '{print $2"_"$1}' $i | sort -V > ${i%.txt}3.txt; done)

I would like to change the name of the file to *_test3.txt, but in my loop I will have the output as *_test23.txt How can I do that?

  • You're doing something else than renaming files there. What's with the awk and sort? – Kusalananda Feb 9 '17 at 16:50
  • Yes, I am using awk to get some specific columns and sort the lines and then generate the new file name. – Alex Feb 9 '17 at 16:51

${i%.txt} will just remove the .txt extension from the filename $i. To pick off one extra character, use ${i%?.txt}:

for i in {a,b,c}/*_test2.txt; do
  awk '{ print $2 "_" $1 }' "$i" | sort -V -o "${i%?.txt}3.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.