如何在Linux中正确使用管道?

如何在Linux中正确使用管道?,linux,shell,Linux,Shell,我有一个项目,目标是提取一个data.txt文件的电话号码,所以我做了一个程序。就像这样: grep -E '^[ ]{0,9}\([0-9]{3}\) [0-9]{3}-[0-9]{4}[ ]{0,9}$' $1 | sed 's/^[ \t]*//' > all-result-phonenumber-filter.txt count=$(wc -l all-result-phonenumber-filter.txt) echo "The number of line is :$

我有一个项目,目标是提取一个data.txt文件的电话号码,所以我做了一个程序。就像这样:

   grep -E '^[ ]{0,9}\([0-9]{3}\) [0-9]{3}-[0-9]{4}[ ]{0,9}$' $1 | sed 's/^[ \t]*//' > all-result-phonenumber-filter.txt
count=$(wc -l all-result-phonenumber-filter.txt)

echo "The number of line is :$count" >> all-result-phonenumber-filter.txt
我的问题是,当我想使用这个程序并在我的终端上执行时,我必须使用pipe作为我的终端命令。我在终端上尝试了许多不同的命令,最后一个命令是:

cat data.txt | ./all-phone-number-filter.sh | cat all-result-phonenumber-filter.txt
但是这个命令不起作用,我也不知道为什么。那么,对于上述格式,我必须使用的正确命令是什么

我必须为管道使用以下格式SDTIN | STDOUT

我为您提供data.txt文件:

(512) 258-6589

(205) 251-6584

(480) 589-9856

(303) 548-9874

(808) 547-3215

(270) 987-6547

(225) 258-9887

(314) 225-2543

(979) 547-6854

(276) 225-6985

les numeros suivants ne sont pas valables pour ce programme :

+512 325

+512 251 2545654654

+512 6546 6464646

+512546546646564646463313

(314) sgf225-2543

(314) 225-2543fsgaf

(314afd) 225-2543

FSd(314) 225-2543
我需要的结果是:

  (512) 258-6589
(205) 251-6584
(480) 589-9856
(303) 548-9874
(808) 547-3215
(270) 987-6547
(225) 258-9887
(314) 225-2543
(979) 547-6854
(276) 225-6985
The number of line is :10 all-result-phonenumber-filter.txt
试试这个:

cat data.txt | ./all-phone-number-filter.sh > all-result-phonenumber-filter.txt
若要在上查看结果,请执行下一个命令

cat all-result-phonenumber-filter.txt
过滤器将:

  • 从标准文本中读取
  • 写信给stdout
您的程序将:

  • 从标准文本中读取
  • 写入硬编码的文件名
所以你的程序不是一个过滤器,也不能像你想要的那样使用

将程序转换为筛选器的最简单/最糟糕的方法是改为写入临时文件,然后
cat

#!/bin/sh
# TODO: Rewrite to be a nicer filter that doesn't write to files
tmp=$(mktemp)
grep -E '^[ ]{0,9}\([0-9]{3}\) [0-9]{3}-[0-9]{4}[ ]{0,9}$' $1 | sed 's/^[ \t]*//' > "$tmp"
count=$(wc -l < "$tmp")

echo "The number of line is :$count" >> "$tmp"
cat "$tmp"
rm "$tmp"

您是否正在尝试将结果保存到名为“all result phonenumber filter.txt”的文件中?您的程序不是筛选器,因此无法以这种方式运行它。您可以改为运行它,例如,
cat data.txt |/all-phone-number-filter.sh;cat all result phonenumber filter.txt
您能给我一个类似过滤器的程序示例吗?因为我不知道如何才能做到这一点?我也想在终端上显示,当我在终端上输入命令时,我想在终端上和.txt文件中显示结果,然后只需对文件进行cat即可-请参阅更新的回答如果我想显示我的文件的所有内容。txt我可以在命令末尾写些什么?这是一个示例。您可以使用
cat data.txt./all-phone-number-filter.sh|tee myfile.txt
$ cat data.txt | ./all-phone-number-filter.sh | tail -n 3
(979) 547-6854
(276) 225-6985
The number of line is :10

$ cat data.txt | ./all-phone-number-filter.sh > myfile.txt
(no output)

$ nl myfile.txt | tail -n 5
 7  (225) 258-9887
 8  (314) 225-2543
 9  (979) 547-6854
10  (276) 225-6985
11  The number of line is :10