首页 > 解决方案 > 将字符串放在一起(变量加管道)

问题描述

目标是使用静态变量并将其与管道的输出相结合。我正在寻找单线解决方案!

这是对书面示例的全面检查,以使其更加干净!我已经删除了导致噪音的旧帖子。

link="http://example.com/"
echo "index.html" > test.file
echo "search.php" >> test.file
echo "login.js" >> test.file

cat test.file | awk 'BEGIN {var=ARGV[1];ARGV[1]=""} {print var, $0}' "$link"
http://example.com/ index.html
http://example.com/ search.php
http://example.com/ login.js

cat test.file | awk -v var="$link" '{print var, $0}'
http://example.com/ index.html
http://example.com/ search.php
http://example.com/ login.js

这看起来像我需要的,但里面没有讨厌的空白。我需要那个场分离消失!选项-F''导致错误消息。添加| tr| sed删除 while 空间对我来说似乎是错误纠正。

到目前为止,以下解决方案有效...

for string in $(cat test.file)
do
    printf "${link}%s\n" "$string"
done

输出:

http://example.com/index.html
http://example.com/search.php
http://example.com/login.js

在一个循环中,我可以将管道的所有输出与我的静态变量结合起来。但是不使用循环难道没有更好的解决方案吗?

默认情况下,接近管道似乎printf不起作用,我必须投入xargs使用。

echo "World" | xargs printf 'Hello %s\n' "$1"
Hello
Hello World

即使这样,产量也翻了一番,但为什么呢?

我仍在寻找单线解决方案!

标签: bash

解决方案


您通过管道将某些内容输入printf,但printf不处理其标准输入。您可以通过执行以下操作轻松验证这一点

echo x | printf foo%s bar

它只打印 foobar,并忽略x


推荐阅读