Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append wc lines to filename

Title says it all. I've managed to get just the lines with this:

lines=$(wc file.txt | awk {'print $1'});

But I could use an assist appending this to the filename. Bonus points for showing me how to loop this over all the .txt files in the current directory.

like image 338
Andrew Hall Avatar asked Mar 11 '23 01:03

Andrew Hall


1 Answers

find -name '*.txt' -execdir bash -c \
  'mv -v "$0" "${0%.txt}_$(wc -l < "$0").txt"' {} \;

where

  • the bash command is executed for each (\;) matched file;
  • {} is replaced by the currently processed filename and passed as the first argument ($0) to the script;
  • ${0%.txt} deletes shortest match of .txt from back of the string (see the official Bash-scripting guide);
  • wc -l < "$0" prints only the number of lines in the file (see answers to this question, for example)

Sample output:

'./file-a.txt' -> 'file-a_5.txt'
'./file with spaces.txt' -> 'file with spaces_8.txt'
like image 88
Ruslan Osmanov Avatar answered Mar 20 '23 17:03

Ruslan Osmanov