Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何在for循环中回送变量而不丢失空间?_Bash_Shell_For Loop_Echo - Fatal编程技术网

Bash 如何在for循环中回送变量而不丢失空间?

Bash 如何在for循环中回送变量而不丢失空间?,bash,shell,for-loop,echo,Bash,Shell,For Loop,Echo,我想循环文件的每一行。如果它包含标记,则在不丢失空间的情况下显示整行 但如果我的代码如下所示,它会将空格转换为返回: $ cat testfile first line mark apple second line not banana third line mark pear 输出为 for i in `cat testfile | grep mark`; do echo $i done for i in `cat testfile | grep mark`; do pri

我想循环文件的每一行。如果它包含
标记
,则在不丢失空间的情况下显示整行

但如果我的代码如下所示,它会将空格转换为返回:

$ cat testfile
first line mark apple
second line not banana
third line mark pear
输出为

for i in `cat testfile | grep mark`; do
    echo $i
done
for i in `cat testfile | grep mark`; do
    printf $i
done
如果使用printf

first
line
mark
apple
third
line
mark
pear
输出为

for i in `cat testfile | grep mark`; do
    echo $i
done
for i in `cat testfile | grep mark`; do
    printf $i
done
如何获得以下输出:

firstlinemarkapplethirdlinemarkpear
这应该可以:

first line mark apple
third line mark pear
这应该可以:

first line mark apple
third line mark pear
最简单的方法是:

grep mark testfile
不需要循环。没有


但是如果你想理解为什么你的循环不起作用,那是因为你在grep的输出中循环每个单词。要在每行上循环,您需要使用
读取

grep mark testfile

不过,这是很多不必要的代码。读每一行只是为了把它们吐出来?最好省略整个循环。

最简单的方法是:

grep mark testfile
不需要循环。没有


但是如果你想理解为什么你的循环不起作用,那是因为你在grep的输出中循环每个单词。要在每行上循环,您需要使用
读取

grep mark testfile


不过,这是很多不必要的代码。读每一行只是为了把它们吐出来?最好省略整个循环。

谢谢大家的回复,在转换为grep模式文件后,脚本如下,请告诉我它是否合适:

cat testfile | grep mark | while IFS= read -r line; do
    echo "$line"
done

谢谢大家的回复,转换成grep模式文件后,脚本如下,请告诉我是否合适:

cat testfile | grep mark | while IFS= read -r line; do
    echo "$line"
done

grep mark testfile我正要为“$(grep mark testfile)”中的i建议
;做回显“$i”;完成
,但它将
$i
设置为
grep
命令的整个多行输出,而不是按行进行迭代。grep mark testfile我正要为“$(grep mark testfile)”中的i建议
;做回显“$i”;完成
,但它将
$i
设置为
grep
命令的整个多行输出,而不是按行迭代。这很完美。但除此之外,在grep之后,我的脚本需要循环结果,并将最后一个单词提取到一个函数中以测试其模式,如果匹配,则打印整行。如果是这样的话,我应该在
grep mark testfile
中使用for I吗;做恐怕这样,它又破裂了?太好了。但除此之外,在grep之后,我的脚本需要循环结果,并将最后一个单词提取到一个函数中以测试其模式,如果匹配,则打印整行。如果是这样的话,我应该在
grep mark testfile
中使用for I吗;做恐怕就这样,它又坏了?