Append wc lines to filename

2019-06-26 06:44发布

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.

9条回答
看我几分像从前
2楼-- · 2019-06-26 07:08
{ linecount[FILENAME] = FNR }
END {
    linecount[FILENAME] = FNR
    for (file in linecount) {
        newname = gensub(/\.[^\.]*$/, "-"linecount[file]"&", 1, file)
        q = "'"; qq = "'\"'\"'"; gsub(q, qq, newname)
        print "mv -i -v '" gensub(q, qq, "g", file) "' '" newname "'"
    }
    close(c)
}

Save the above awk script in a file, say wcmv.awk, the run it like:

awk -f wcmv.awk *.txt

It will list the commands that need to be run to rename the files in the required way (except that it will ignore empty files). To actually execute them you can pipe the output to a shell for execution as follows.

awk -f wcmv.awk *.txt | sh

Like it goes with all irreversible batch operations, be careful and execute commands only if they look okay.

查看更多
地球回转人心会变
3楼-- · 2019-06-26 07:11

This would work, but there are definitely more elegant ways.

for i in *.txt; do
  mv "$i" ${i/.txt/}_$(wc $i | awk {'print $1'})_.txt; 
done

Result would put the line numbers nicely before the .txt. Like:

file1_1_.txt 
file2_25_.txt
查看更多
Luminary・发光体
4楼-- · 2019-06-26 07:16

you can do like this as well:

for file in "path_to_file"/'your_filename_pattern'
    do
      lines=$(wc $file | awk {'print $1'})
      mv $file $file'_'$lines
    done

example:

    for file in /oradata/SCRIPTS_EL/text*
    do
        lines=$(wc $file | awk {'print $1'})
        mv $file $file'_'$lines
    done
查看更多
Luminary・发光体
5楼-- · 2019-06-26 07:17
#/bin/bash

files=$(find . -maxdepth 1 -type f -name '*.txt' -printf '%f\n')
for file in $files; do
    lines=$(wc $file | awk {'print $1'});
    extension="${file##*.}"
    filename="${file%.*}"
    mv "$file" "${filename}${lines}.${extension}"
done

You can adjust maxdepth accordingly.

查看更多
倾城 Initia
6楼-- · 2019-06-26 07:23
 awk '
  BEGIN{ for ( i=1;i<ARGC;i++ ) Files[ARGV[i]]=0 }

  {Files[FILENAME]++}

  END{for (file in Files) {
        # if( file !~ "_" Files[file] ".txt$") {

           fileF=file;gsub( /\047/, "\047\"\047\"\047", fileF)
           fileT=fileF;sub( /.txt$/, "_" Files[file] ".txt", fileT)

           system( sprintf( "mv \047%s\047 \047%s\047", fileF, fileT))

        #   }
        }
     }' *.txt

Another way with awk to manage easier a second loop by allowing more control on name (like avoiding one having already the count inside from previous cycle)

Due to good remark of @gniourf_gniourf:

  • file name with space inside are possible
  • tiny code is now heavy for such a small task
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-06-26 07:24

Use rename command

for file in *.txt; do 
 lines=$(wc ${file} | awk {'print $1'});
 rename s/$/${lines}/ ${file}
done
查看更多
登录 后发表回答