[英]how to use values with sed in shell scripting?
我正在尝试用字母表编写 shell 脚本,
我有5个这样的参数
$alphametic 5790813 BEAR RARE ERE RHYME
要得到
ABEHMRY -> 5790813
我试过这个:
#!/bin/bash
echo "$2 $3 $4 $5" | sed 's/ //g ' | sed 's/./&\n/g' | sort -n | sed '/^$/d' | uniq -i > testing
paste -sd '' testing > testing2
sed "s|^\(.*\)$|\1 -> ${1}|" testing2
但我收到错误(使用最后一个命令sed
),我不知道问题出在哪里。
#!/bin/sh
val="$1"
shift
printf '%s' "$@" | awk -v FS='' -v OFS='\n' '{$1=$1}1' | sort -n | uniq | tr -d '\n'
printf " -> %s\n" "$val"
编辑: output 中的固定顺序
shift
从 arguments 中移除$1
。 然后$@
将包含所有 arguments 但第一个,旧的$2
将是$1
, $3
将是$2
,等等...printf '%s' "$@"
将所有 arguments 连接成一个字符串awk -v FS='' -v OFS='\n' '{$1=$1}1'
垂直输出每个字符tr -d '\n'
删除所有\n
字符备注:我没有将-i
选项添加到uniq
因为我的操作系统无法识别它。
一个想法使用awk
来完成整个事情:
arg1="$1"
shift
others="$@"
awk -v arg1="${arg1}" -v others="${others}" '
BEGIN { n=split(others,arr,"") # split into into array of single characters
for (i=1;i<=n;i++) # loop through indices of arr[] array
letters[arr[i]] # assign characters as indices of letters[] array; eliminates duplicates
delete letters[" "] # delete array index for "<space>"
PROCINFO["sorted_in"]="@ind_str_asc" # sort array by index
for (i in letters) # loop through indices
printf "%s", i # print index to stdout
printf " -> %s\n", arg1 # finish off line with final string
}
'
注意: PROCINFO["sorted_in"]
需要GNU awk
(对letters[]
数组的索引进行排序)
这会产生:
ABEHMRY -> 5790813
另一种方法:
chars=$(printf '%s' "${@:2}" | fold -w1 | sort -u | paste -sd '')
echo "$chars -> $1"
sort 的-n
在这里没有意义:这些是字母,而不是数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.