gpt4 book ai didi

linux - 删除字符串前的空格

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:46 24 4
gpt4 key购买 nike

我想使用管道计算某个文件中字符串的出现次数,而不使用 awk 和 sed 命令。

我的文件内容:

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 )

由于这两个字符串前面有空格(我用 _ 标记),因此不计算 Sort 和 less 命令。我应该如何改进我的代码,以删除“sort”和“less”之前的空格?提前致谢!

更新:这是输入文件的第二个更长的示例:

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 {}

最佳答案

如您所知,问题中代码的问题在于 cut 语句。这将 cut 替换为还包含 basename 命令的 shell while 循环:

$ 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

关于linux - 删除字符串前的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29783613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com