[英]How to combine two different rows by using awk sed or shell script
我有一個文件file.txt。 我必須將兩個不同的行合並為一個。
file.txt的
linux-
02-10-2018 11:50 is-a-opensource user file
02-10-2018 11:46 linux-userfile user file1
user-1
02-10-2018 11:40 linux-userfile user file2
linux- user-2
02-10-2018 11:30 linux-userfile user file3
預期產量
02-10-2018 11:50 linux-is-a-opensource user file
02-10-2018 11:46 linux-userfile user file1
02-10-2018 11:40 linux-userfile user1user file2
02-10-2018 11:30 linux-linux-userfile user-2user file3
任何建議將不勝感激。
我嘗試使用下面的命令,但沒有這樣做。
$ awk ' /^ +/{ gsub(/^ +/," ");a=a $0; next }{ $2=$2a;a=""}1' file.txt
我遇到錯誤了
02-10-2018 11:50 linux- is-a-opensource user file
02-10-2018 11:46 linux-userfile user file1
02-10-2018 11:40 user-1 linux-userfile user file2
02-10-2018 11:30 linux- user-2 linux-userfile user file3
並且我嘗試了以下鏈接以供參考,但仍然出現相同的錯誤如何使用awk在Linux中合並2條不同的行
由於很難確定字符串屬於哪一列,因此我作以下假設:
因此以下awk腳本將假定:
注意:如果您的文件與空格對齊(制表符和空格的組合),則我們不能使用字段分隔符“ \\ t”來區分字段,因為制表符的數量取決於字段的寬度。
這是經過測試的腳本:
# If you have a tab-aligned file, replace all tabs by the
# correct sequence of spaces. In this example, we assume a single
# tab is equivalent to 8 spaces. Adopt if needed
{ gsub(/\t/," ",$0) }
# If the line does not start with a combination of numbers and hyphens
# it is a line that needs to be merged into the next line.
# store it and move to the next line
($1 !~ /^[-0-9]+$/) { tomerge=$0; next }
# If we picked up a tomerge line, try to figure out the fields
# by looking into the current line and determining the field widths.
(tomerge != "") {
# extract fields
n=1
for(i=1;i<NF;++i) {
m=index($0,$(i+1))
field[i]=substr(tomerge,n,m-n)
sub(/^[[:blank:]]*/,"",field[i]) # remove leading blanks
sub(/[[:blank:]]*$/,"",field[i]) # remove trailing blanks
n=m
}
field[NF]=substr(tomerge,n)
# perform merging
for(i=1;i<=NF;++i) $i= field[i] $i
# reset the tomerge value
tomerge=""
}
# print the line
{ $1=$1;print $0 }
輸出:
$ awk -f script.awk file.txt
02-10-2018 11:50 linux-is-a-opensource user file
02-10-2018 11:46 linux-userfile user file1
02-10-2018 11:40 linux-userfile user-1user file2
02-10-2018 11:30 linux-linux-userfile user-2user file3
如果要對齊,可以將其傳遞給column -t
$ awk -f script.awk file.txt | column -t
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.