我想使用管道来计算某些文件中字符串的出现,没有awk和sed命令。
my_file内容:
ls -al
bash
cat datoteka.txt
cat d.txt | sort | less
/bin/bash
我使用的终端命令:
cat $my_file | cut -d ' ' -f 1 | tr '|' '\n' | xargs -r -L1 basename | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0'
期望的输出:
bash 2
cat 2
less 1
ls 1
sort 1
In my case, I get:
bash 2
cat 2
ls 1
_sort 1 (not counted )
_less 1 (not counted )
由于这两个字符串前面的空格(我标有_),因此不计算排序和较少的命令。如何改进我的代码,在“排序”和“减少”之前删除这个空格?提前谢谢!
更新:以下是输入文件的第二个较长示例:
nl /etc/passwd
seq 1 10 | tr "\n" ","
seq 1 10 | tr -d 13579 | tr -s "\n "
seq 1 100 | split -d -a 2 -l10 - blabla-
uname -a | cut -d" " -f1,3
cut -d: -f1 /etc/passwd > fst
cut -d: -f3 /etc/passwd > scnd
ps -e | column
echo -n ABC | wc -m -c
cmp -s dat1.txt dat1.txt ; echo $?
diff dat1 dat2
ps -e | grep firefox
echo dat1 dat2 dat3 | tr " " "\n" | xargs -I {} -p ln -s {}
答案 0 :(得分:1)
正如您所知,问题中代码的问题在于cut
语句。这将cut
替换为包含while
命令的shell basename
循环:
$ tr '|' '\n' <my_file | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0'
bash 2
cat 2
less 1
ls 1
sort 1
以上按命令名称的字母顺序对结果进行排序。如果我们想要按出现次数的降序排序,那么:
tr '|' '\n' <file2 | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0' | sort -snrk2
将此命令应用于问题中的第二个输入示例:
$ tr '|' '\n' <file2 | while read cmd other; do basename "$cmd"; done | sort | uniq -c | xargs -r -L1 sh -c 'echo $1 $0' | sort -snrk2
tr 4
cut 3
seq 3
echo 2
ps 2
cmp 1
column 1
diff 1
grep 1
nl 1
split 1
uname 1
wc 1
xargs 1
答案 1 :(得分:1)
while IFS='|' read -ra commands; do
for cmd in "${commands[@]}"; do
set -- $cmd # unquoted to discard irrelevant whitespace
basename $1
done
done < myfile |
sort |
uniq -c |
while read num cmd; do
echo "$cmd $num"
done
bash 2
cat 2
less 1
ls 1
sort 1