如何仅使用sed工具合并两个文件,生成指定配对格式的文件?
Using sed to Merge Two Files into Name-Link Pairs
Got it, let's break down how to use sed to combine your two files into the desired "Name Link" format. Since file2 has the exact same link repeated across all 5 lines, we can optimize this instead of processing every line of file2.
Method 1: Process Both Files Directly with sed
This approach reads file2 first, captures the link once, then pairs it with each line from file1:
sed -e '1{h;d}' -e 'G;s/\n/ /' file2 file1 > file3
Let's unpack what each part does:
1{h;d}: When processing the first line of file2 (the first input file), we copy that line to sed's "hold space" (h) and then delete the line from the pattern space (d) so it doesn't get printed. This stores our link for later use.G: For every subsequent line (which will be from file1), we append the content of the hold space (our link) to the current line, separated by a newline.s/\n/ /: We replace that newline separator with a space, turning "name\nlink" into "name link".- The final
> file3writes the merged output to your target file.
Method 2: Extract the Link First, Then Append to File1
If you prefer a more readable approach, you can first grab the link from file2, then use sed to add it to the end of each line in file1:
# Capture the link from the first line of file2 LINK=$(head -n 1 file2) # Append the link to each line in file1 sed "s/$/ $LINK/" file1 > file3
Here's why this works:
LINK=$(head -n 1 file2): We useheadto get just the first line of file2 (since all lines are identical) and store it in a variable.sed "s/$/ $LINK/": Thes/$/.../command replaces the end of each line in file1 with a space plus our stored link, resulting in the exact "Name Link" format you need.
Either method will give you the file3 output you're looking for. Test them out to see which fits your workflow better!
内容的提问来源于stack exchange,提问作者bob
相关产品推荐
相关产品推荐

