我有一个如下格式的文本文件。第一行是“KEY”,第二行是“VALUE”。

KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1

我需要这个值和键在同一行。所以输出应该是这样的…

KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1

如果我可以使用一些分隔符,如$或:

KEY 4048:1736 string , 3

我如何将两条线合并成一条?


当前回答

"ex"是一个可脚本化的行编辑器,与sed、awk、grep等属于同一家族。我觉得这可能就是你要找的东西。许多现代vi克隆/后继者也有一个vi模式。

 ex -c "%g/KEY/j" -c "wq" data.txt

这就是说,对于每一行,如果它匹配"KEY"执行下一行的j。该命令完成后(针对所有行),发出一个w rite和q uit。

其他回答

nawk '$0 ~ /string$/ {printf "%s ",$0; getline; printf "%s\n", $0}' filename

这读起来是

$0 ~ /string$/  ## matches any lines that end with the word string
printf          ## so print the first line without newline
getline         ## get the next line
printf "%s\n"   ## print the whole line and carriage return

在我需要合并两行(为了更容易处理),但允许数据超过特定的情况下,我发现这是有用的

data.txt

string1=x
string2=y
string3
string4
cat data.txt | nawk '$0 ~ /string1=/ { printf "%s ", $0; getline; printf "%s\n", $0; getline } { print }' > converted_data.txt

然后输出如下:

converted_data.txt

string1=x string2=y
string3
string4

使用vim的另一个解决方案(仅供参考)。

解决方案1:

打开vim vim文件名中的文件,然后执行命令:% normal Jj

这个命令很容易理解:

%:对于所有的行, Normal:执行正常命令 京晶:执行Join命令,然后跳转到线下

然后,保存文件并以:wq退出

解决方案2:

在shell中执行命令,vim -c ":% normal Jj" filename,保存文件并以:wq退出。

更通用的解决方案(允许连接多个后续行)是shell脚本。这在每一个之间增加了一条线,因为我需要可见性,但这很容易补救。在这个例子中,“key”行以:结尾,而其他行没有。

#!/bin/bash
#
# join "The rest of the story" when the first line of each   story
# matches $PATTERN
# Nice for looking for specific changes in bart output
#

PATTERN='*:';
LINEOUT=""
while read line; do
    case $line in
        $PATTERN)
                echo ""
                echo $LINEOUT
                LINEOUT="$line"
                        ;;
        "")
                LINEOUT=""
                echo ""
                ;;

        *)      LINEOUT="$LINEOUT $line"
                ;;
    esac        
done

awk:

awk 'NR%2{printf "%s ",$0;next;}1' yourFile

注意,在输出的末尾有一个空行。

sed:

sed 'N;s/\n/ /' yourFile