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

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

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

问题

#!/bin/bash
# loop on all .txt files
for i in File1.txt; do
  # remove first column and add extra field
  awk '{print NR, $0}' $i | cut -d' ' -f2- >> File3.txt
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 .

#!/bin/bash
#  loop on all .txt files
for i in File1.txt; do
#  remove first column
cut -d' ' -f2- < $i > File2.txt
done  

#!/bin/bash
filename='File2.txt'
while read line; do
# reading each line
echo "$RANDOM $line" >> File3.txt
done < $filename


File1.txt
Date Field2 Field3
20111 aaaa  bbbb
33111 bbbb  vvvv
44444 cccc  gggg

File2.txt
Field2 Field3
aaaa  bbbb
bbbb  vvvv
cccc  gggg

File3.txt
New  Field2 Fileld3
1    aaaa  bbbb
2    bbbb  vvvv
1    cccc  gggg

答案1

得分: 1

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

一个想法:

    new="新的"
    
    while read -r ignore rest_of_line
    do
        echo "$new $rest_of_line"
        new=$RANDOM
    done < file1.txt > file3.txt

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

$ cat file3.txt
新的 Field2 Field3
29258 aaaa  bbbb
31885 bbbb  vvvv
15550 cccc  gggg

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

英文:

One idea:

new=&quot;New&quot;

while read -r ignore rest_of_line
do
    echo &quot;$new $rest_of_line&quot;
    new=$RANDOM
done &lt; file1.txt &gt; file3.txt

This generates:

$ cat file3.txt
New Field2 Field3
29258 aaaa  bbbb
31885 bbbb  vvvv
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:

确定