开发者

Sed to wrap lines in text file?

开发者 https://www.devze.com 2023-02-16 01:51 出处:网络
I am a newbie with Sed. I have a bunch of ASCII files containing data that\'s laid out like so: Test_Version:2.6.3

I am a newbie with Sed. I have a bunch of ASCII files containing data that's laid out like so:

Test_Version:2.6.3
Model-Manufacturer:
HR21-100
Test_Version:2.6.3
Model-Manufacturer:
D12-100

All I want to do is fold the lines for "Model-Manufacturer:" like this:

T开发者_开发百科est_Version:2.6.3
Model-Manufacturer:HR21-100
Test_Version:2.6.3
Model-Manufacturer:D12-100

I tried to use sed since I discovered there are 2 hex values (0xA for \n) after "Model-Manufacturer:"

cat myfile| sed -n "/[[:xdigit:]]\{2\}/p"

The output looked like this for my match code:

Model-Manufacturer:
HR21-100
Model-Manufacturer:
D12-100

This tells me I am on the right track, right? What I cannot figure out is the proper match/replace code to fold the lines for "Model-Manufacturer:". A attempt with

cat myfile| sed "s/[[:xdigit:]]\{3\}//g"

completed messed up my file. Any idea how to do this?


$ cat test.txt
Test_Version:2.6.3
Model-Manufacturer:
HR21-100
Test_Version:2.6.3
Model-Manufacturer:
D12-100

$ cat test.txt | sed -e '/:$/N; s/:\n/:/'
Test_Version:2.6.3
Model-Manufacturer:HR21-100
Test_Version:2.6.3
Model-Manufacturer:D12-100

Here's a break down of each sed command.

/:$/N

If the input line has a ':' at the end, insert a newline at the end of the pattern space and append the next line of input.

s/:\n/:/

Replace a ":" followed by a newline with ":", removing the newline.


The bracket expression [[:xdigit:]] matches any of the text characters 01234567890abcdefABCDEF. That's the reason it appears to match using what you tried - because there are "e", "a", "1", "2" and "0" characters in those lines. If you wanted to match any non-printing character, you could use [[:cntrl:]]. However, to specifically match a newline, you can use \n, \x0a, \o12 or \d10.

However, that's not really what you want to do since sed doesn't see the newline at the end of each line. It only sees them if they're embedded in lines that it appends together.

Here's a sed command that appends the lines together that you want:

sed '/Model-Manufacturer:/{N;s/\n//}' myfile

Explanation:

  • /Model-Manufacturer:/{ - If a line matches "Model-Manufacturer:"
    • N - Append the next line
    • s/\n// - Remove the embedded newline added by the append operation
  • } - end if


you can also use awk

gawk '/Model/{printf $0;getline;print;next}1' file
0

精彩评论

暂无评论...
验证码 换一张
取 消