简体   繁体   中英

Output to specific areas of a file to another file using awk or sed?

I have a file that looks like this:

d "Text 1":6,64;1 /filesys1/db1.d2
d "Text 2":6,64;1 /filesys1/db1.d2 f 730
d "Text 3":6,64;1 /filesys1/db1.d2 
d "TextA":6,64;1 /filesys1/db1.d2 f 46000
d "TextB":6,64;1 /filesys1/db1.d2
d "TextC":6,64;1 /filesys1/db1.d2 f 120000
...

I need to get everything from between the quotes and then the last 2 characters of the line and put it in a new file. I can do the two pieces separately but I can't combine them and get it to work.

awk -F'"' '$0=$2' datatmp4 > dataout2

will get me:

Text 1
Text 2
Text 3
TextA
TextB
TextC

and

awk '{ print substr( $NF, length($NF) -1, length($NF) ) }' datatmp4 > dataout

will get me:

d2
30
d2
00
d2
00

what I need is:

Text 1 d2
Text 2 30
Text 3 d2
TextA 00
TextB d2
TextC 00

您可以使用$ 2连接引号之间的文本以及最后2个字符的结果,如下所示:

awk -F '"' '{print $2, substr($NF, length($NF)-1, length($NF))}' datatmp4 > dataout

You're making things too hard on yourself. There's no reason to care about or try to operate on the last field on the line ($NF) when all you want is the last 2 characters of the whole line:

$ awk -F'"' '{print $2, substr($0,length()-1)}' file
Text 1 d2
Text 2 30
Text 3 2
TextA 00
TextB d2
TextC 00

The third line of output ends in 2<blank> because that's what was in your input file. That doesn't match your posted desired output though so be clear - do you want the last chars of each line as I've shown and you said you wanted, or do you want the last 2 non-blank chars as implied by your posted desired output?

$ awk -F"\"" '{match($NF,/..$/,a); print $2,a[0]}' last2
Text 1 d2
Text 2 30
Text 3 2
TextA 00
TextB d2
TextC 00

With sed (BRE):

sed 's/^[^"]*"\([^"]*\).*\(.[^ ]\)/\1 \2/;' file

Another way with sed (ERE):

sed -E 's/^[^"]*"|"[^ ]*( ).*(.[^ ])/\1\2/g' file

With awk:

awk -F'"' '{ print $2 " " gensub(/.*(.[^ ])/, "\\1", 1)}' file

The field separator is a quote. gensub replaces all characters from line except the 2 last characters (the second must not be a space).

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