如何使用 awk 或 sed 在 csv 文件中的每行末尾添加 wc -l 的输出

如何使用 awk 或 sed 在 csv 文件中的每行末尾添加 wc -l 的输出

我试图wc -l在文件的每一行末尾添加 的输出。如果一个文件有 20 条记录/行,我想在该文件的每行末尾添加数字 20,如果下一个文件有 100 条记录/行,则在每行末尾添加 100。我尝试了以下命令,但没有执行我想要的操作。

awk -v char=$(wc -l FILENAME | cut -f1 -d' ') '{print $0"," char}' FILENAME

答案1

这是一个奇怪的请求,但这应该可以满足您的要求。

#!/bin/bash

shopt -s nullglob

for f in *.csv; do
   size="$(wc -l <$f)"
   sed -i "s/$/,$size/g" "$f"
done

exit

请注意,这将就地编辑.csv当前目录中的每个文件。

编辑:在 Mac 上,您的sed命令可能必须是,sed -i '.bak' "s/$/, $size/g" "$f"因为可能需要备份扩展。不过,这在我的 Linux 机器上不起作用。

答案2

纯 awk 的解决方案:

awk '
  # Read the file and print it with the additional column
  function process_file( SIZE, FILE,    NEW_FILE ) {
    NEW_FILE = FILE ".tmp"
    while ( ( getline < FILE ) > 0 ){
      print $0 "," SIZE > NEW_FILE
    }
    close( FILE )
    close( NEW_FILE )
    system( "mv -f " NEW_FILE " " FILE )
  }

  # File name has changed, we just passed the end of a file,
  # => print the current file
  ( NR > 1 ) && ( PREV_FILE != FILENAME ) {
    process_file( OLD_FNR, PREV_FILE )
  }

  {
    # Save the current file name and line number within the file
    PREV_FILE = FILENAME
    OLD_FNR = FNR
  }

  END {
    # Print the last file, if any
    if ( PREV_FILE != "" ) {
      process_file( OLD_FNR, PREV_FILE )
    }
  }' file1 file2 ...

这是更容易与呆呆地,其中有一个文件结束健康)状况:

gawk '
  # Read the file and print it with the additional column
  function process_file( SIZE, FILE,    NEW_FILE ){
    NEW_FILE = FILE ".tmp"
    while ( ( getline < FILE ) > 0 ){
      print $0 "," SIZE > NEW_FILE
    }
    close( FILE )
    close( NEW_FILE )
    system( "mv -f " NEW_FILE " " FILE )
  }
  # End of a file, print the file
  # FILENAME is the name of the current file being read
  # FNR is the line number within the file
  ENDFILE {
    process_file( FNR, FILENAME )
  }' file1 file2 ...

答案3

它不是 awk,但工作起来很简单

number=$(wc -l $1 | cut -d ' ' -f 1)
sed -i "s/\$/ ${number}/" $1

或者如果你喜欢将其放在一行中:

sed -i "s/\$/ $(wc -l $file | cut -d ' ' -f 1)/" $file

例子:

user@server 22:59:58:/tmp$ file='FILENAME'
user@server 23:00:07:/tmp$ for ((i=0; i < 10; i++)) ; do echo 123 >> "$file"; done
user@server 23:00:18:/tmp$ cat "$file"
123
123
123
123
123
123
123
123
123
123
user@server 23:00:25:/tmp$ wc -l "$file"
10 FILENAME
user@server 23:00:30:/tmp$ sed -i "s/\$/ $(wc -l "$file" | cut -d ' ' -f 1)/" "$file"
user@server 23:00:37:/tmp$ cat "$file"
123 10
123 10
123 10
123 10
123 10
123 10
123 10
123 10
123 10
123 10
user@server 23:00:39:/tmp$
user@server 23:01:54:/tmp$ ls -lA "$file"
-rw-r--r-- 1 user user 70 Dez  4 23:00 FILENAME

相关内容