如何读取文件并删除每行的字段,然后为每行添加额外的行。

huangapple go评论94阅读模式
英文:

How to read the file and remove the field of each line then add the extra row to each line

问题

  1. #!/bin/bash
  2. # loop on all .txt files
  3. for i in File1.txt; do
  4. # remove first column and add extra field
  5. awk '{print NR, $0}' $i | cut -d' ' -f2- >> File3.txt
  6. done
英文:

I do have two shell script , read the file(file1) and remove the first field of the file ( output result redirect to the file2)
, then second script again read above modified file (file2) then add extra field to each line (file3),
How to do this in single script without using two shell script .

  1. #!/bin/bash
  2. # loop on all .txt files
  3. for i in File1.txt; do
  4. # remove first column
  5. cut -d' ' -f2- < $i > File2.txt
  6. done
  7. #!/bin/bash
  8. filename='File2.txt'
  9. while read line; do
  10. # reading each line
  11. echo "$RANDOM $line" >> File3.txt
  12. done < $filename
  13. File1.txt
  14. Date Field2 Field3
  15. 20111 aaaa bbbb
  16. 33111 bbbb vvvv
  17. 44444 cccc gggg
  18. File2.txt
  19. Field2 Field3
  20. aaaa bbbb
  21. bbbb vvvv
  22. cccc gggg
  23. File3.txt
  24. New Field2 Fileld3
  25. 1 aaaa bbbb
  26. 2 bbbb vvvv
  27. 1 cccc gggg

答案1

得分: 1

这是一段Shell脚本代码,它从file1.txt文件中读取内容,并按行处理。以下是代码的翻译部分:

  1. 一个想法:
  2. new="新的"
  3. while read -r ignore rest_of_line
  4. do
  5. echo "$new $rest_of_line"
  6. new=$RANDOM
  7. done < file1.txt > file3.txt

这段代码生成的输出如下所示:

  1. $ cat file3.txt
  2. 新的 Field2 Field3
  3. 29258 aaaa bbbb
  4. 31885 bbbb vvvv
  5. 15550 cccc gggg

注意: 目前不清楚输入和输出字段的分隔符是什么,所以我假设输入使用任何空白字符作为分隔符,而输出使用单个空格作为分隔符。根据需求,可以相对容易地进行修改。

英文:

One idea:

  1. new=&quot;New&quot;
  2. while read -r ignore rest_of_line
  3. do
  4. echo &quot;$new $rest_of_line&quot;
  5. new=$RANDOM
  6. done &lt; file1.txt &gt; file3.txt

This generates:

  1. $ cat file3.txt
  2. New Field2 Field3
  3. 29258 aaaa bbbb
  4. 31885 bbbb vvvv
  5. 15550 cccc gggg

NOTE: it's not clear (to me) what the input/output field delimiters are so for now I'm assuming any white space on input and a single space on output; should be (relatively) easy to modify per OP's requirement

huangapple
  • 本文由 发表于 2023年2月10日 05:22:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定