0

I have this simple plat file (file.txt)

a43
test1
abc
cvb
bnm
test2
test1
def
ijk
xyz
test2
kfo

I need all lines between test1 and test2 in two forms, the firte one create two new files like

newfile1.txt :

test1
abc
cvb
bnm
test2

newfile2.txt

test1
def
ijk
xyz
test2

and the second form create only one new file like :

newfile.txt

test1abccvbbnmtest2
test1abccvbbnmtest2

Do you have any propositions?

For the second form. I used this

sed -n '/test1/,/test2/p' file.txt > newfile.txt

But it give me a result like

test1abccvbbnmtest2test1abccvbbnmtest2

I need a return line like :

test1abccvbbnmtest2
test1abccvbbnmtest2
2

2 Answers 2

1

An awk oneliner for the first case:

awk '/^test1/{file++; on=1} on{print >("newfile" file ".txt")} /^test2/{on=0}' file.txt

which says:

  • If test1 found, increment file number and start output (i.e. turn on)
  • If turned on, print line to the file name "newfileFILE.txt", where FILE is the file number.
  • If test2 is found, end output (i.e. turn off)

Then, you can convert the two files to newfile.txt with the shell oneliner:

for file in newfile?.txt; do tr -d '\n' <$file; echo; done > newfile.txt

which says, foreach file, remove all linefeeds.

1

For your second form:

sed -n '/test1/,/test2/p' file.txt | xargs > newfile.txt ; sed 's/test2/&\n/g' newfile.txt | sed -e 's/^[ \t]*//'
  • sed -n '/test1/,/test2/p' file.txt --> capture text between test1 and test2
  • xargs > newfile.txt --> turn text into "row" effectively speaking, altho purpose of xargs perhaps is different.
  • sed 's/test2/&\n/g' newfile.txt --> add newline after "test2" pattern
  • sed -e 's/^[ \t]*//' --> delete spaces at start of each line.

Not the answer you're looking for? Browse other questions tagged .