英文:
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="New"
while read -r ignore rest_of_line
do
echo "$new $rest_of_line"
new=$RANDOM
done < file1.txt > 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论