Bash 从文件中提取单词

Bash 从文件中提取单词,bash,extract,Bash,Extract,如何从一个文件中提取所有单词,每一行中的每个单词? 例如: test.txt This is my sample text 输出: This is my sample text tr命令可以做到这一点 tr [:blank:] '\n' < test.txt 上面的答案不能很好地处理多个空格等。另一种选择是 perl -p -e '$_ = join("\n",split);' test.txt 那会。例如 esben@mosegris:~/ange/linova/build ma

如何从一个文件中提取所有单词,每一行中的每个单词? 例如:

test.txt

This is my sample text
输出:

This
is
my
sample
text

tr命令可以做到这一点

tr [:blank:] '\n' < test.txt

上面的答案不能很好地处理多个空格等。另一种选择是

perl -p -e '$_ = join("\n",split);' test.txt
那会。例如

esben@mosegris:~/ange/linova/build master $ echo "test    test" | tr [:blank:] '\n' 
test



test
但是


这可能适合您:

# echo -e "this     is\tmy\nsample text" | sed 's/\s\+/\n/g'           
this
is
my
sample
text
答案是:

pearl.214> cat file1
a b c d e f pearl.215> perl -p -e 's/ /\n/g' file1
a
b
c
d
e
f
pearl.216> 

这里有一条明显的抨击路线:

for i in $(< test.txt)
do
    printf '%s\n' "$i"
done
以美元表示的i的
编辑更简短:

printf '%s\n' $(< test.txt)
printf“%s\n”$(

仅此而已,不包括特殊(可怜的)情况(处理多个后续单词分隔符/前导/尾随分隔符是通过做正确的事情(TM))。您可以使用$IFS变量调整单词分隔符的概念,请参阅bash手册。

@Chistopher一个小诡辩-您可能需要添加
-s
来压缩空白。
for i in $(< test.txt)
do
    printf '%s\n' "$i"
done
printf '%s\n' $(< test.txt)