简体   繁体   中英

Append specific string to the start of each line of an output file while streaming result of a command to the same file

Not too certain how to word this. I am trying to write a shell command that will append the first part of a file name to the beginning of each line while streaming the result of a command, in a for loop, that will create the lines in the file. At the same time, I am removing certain lines in the stream that I do not want to write in the file. For example, I have 4 files which are pairs, essentially 2 pair of files.

file1.a.txt
1
2

file1.b.txt 
a
b
c

file2.a.txt
3
8
4

file2.b.txt
d
c
c
a

when I run the shell command, I expect to get just one file with first part of file name and whatever the output of my script command is. The script command will always generate a result with number of lines equal to the number of lines in b.txt and certain lines that I do not have a need for Expected result:

result.txt

file1 script result for line containing a in file1.b.txt
file1 script result for line containing b in file1.b.txt
file1 script result for line containing c in file1.b.txt
file2 script result for line containing d in file2.b.txt
file2 script result for line containing c in file2.b.txt
file2 script result for line containing c in file2.b.txt
file2 script result for line containing a in file2.b.txt

What I have so far:

for x in *a.txt; do echo $(x%.*.*};script command result | sed '/^\(/d'| sed '/^0/d' >> result.txt

This is generating the result.txt with correct lines but the name I am trying to append to the start of each line is missing from the start of each line. That is, it is getting printed to the screen, I believe due to echo. I need help getting to my desired result.

I guess you want:

for x in *a.txt; do
   script command result | 
   sed '/^\(/d'| sed '/^0/d' |
   sed "s/^/$x/" >> result.txt
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM