简体   繁体   English

如何从head命令到sed添加到文件的第一行?

[英]How to result from head command to sed to add to the first line of the file?

I would like to add the text which is the result from head command to sed . 我想将head命令的结果添加到sed Can I achieve this in a one liner? 我可以在一个班轮里做到这一点吗?

This is what I have come up so far. 到目前为止,这就是我提出的。

header=`head -n 1 csv1.csv`
sed -e '1 i\'$'\n''$header' another_csv.csv

What I don't know is how do I pass the result from one command to another command. 我不知道如何将结果从一个命令传递给另一个命令。 I tried usnig xargs but no luck. 我尝试过usnig xargs但没有运气。 I don't know how to pass that as a variable. 我不知道如何将其作为变量传递。

除非我缺少任何东西,否则可能是:

head -1 csv1.csv && cat another.csv

This might work for you (GNU sed): 这可能对您有用(GNU sed):

sed -e '1r file2' -e 'q' file1

or perhaps use: 或使用:

head -1 file1 | cat - file2

awk : awk

awk 'NR==1{getline h<"csv1.csv";print h}7 ' another.csv

test: 测试:

kent$  head f c
==> f <==
1
2
3
4
5

==> c <==
10
9
8

kent$  awk 'NR==1{getline h<"c";print h}7 ' f
10
1
2
3
4
5

gnu sed 古努塞德

kent$  sed '1s/.*/head -n 1 c;echo &/ge' f 
10
1
2
3
4
5

@anubhava's solution is simpler, but just to show the corrected version of the OP's approach: @anubhava的解决方案比较简单,但是只是为了展示OP方法的正确版本:

Linux 的Linux

sed -e "1 i $(head -n 1 csv1.csv)" another_csv.csv
  • On Linux you need not place the text passed to i on a separate line (thus no need for \\ and the literal newline ( $'\\n' ). 在Linux上,您不需要将传递给i的文本放在单独的行上(因此不需要\\和文字换行符( $'\\n' )。
  • In the original approach, '$header' was placed in single quotes, preventing string interpolation - double quotes are needed: "$header" (in my reformulation I used double quotes for the entire sed command (not recommended in general) and directly placed the command inside, using command substitution ( $(...) ). 在原始方法中,将'$header'放在引号中,以防止字符串插值-需要使用双引号: "$header" (在我的改写中,我对整个sed命令使用了双引号(一般不建议),然后直接放置内部命令,使用命令替换( $(...) )。

OSX OSX

Same as above, except \\ and a newline ( $'\\n' ) must be inserted right after the i : 与以上相同,除了\\i之后必须插入换行符( $'\\n' ):

sed -e '1 i\'$'\n'"$(head -n 1 csv1.csv)" another_csv.csv

(The equivalent of: (相当于:

sed -e "1 i\\
$(head -n 1 csv1.csv)
" another_csv.csv

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM