[英]how to determine a newline in bash?
一份文件:
a
b
运行命令
dd if=file count=1 skip=0 bs=1 # show a
dd if=file count=1 skip=1 bs=1 # show "newline"
dd if=file count=1 skip=2 bs=1 # show b
我想在给定偏移量之前搜索第一个“换行符”的偏移量,在 bash 脚本中使用“if”语句(这是一种虚拟方式):
para1=$1
while(1)
do
c=$(dd if=file count=1 bs=1 skip=$para1)
if [ $c -eq "\n" ] # How to write this line?
then
break
fi
para1=`expo $para - 1`
done
echo $para1
bash fun.sh 2
# the output should be 1
实际上我在这里找到了一个解决方案: 我如何比较我的变量是否在 shell 脚本中包含换行符
if [ ${#str} -eq 0 ]
但我想知道它是否足够强大,还是有更优雅的方法来做到这一点?
请关注代码:
c=$(dd if=test1 skip=2 bs=1 count=1)
man bash
的命令替换部分描述:
Bash 通过执行命令执行扩展...删除任何尾随换行符。
因此,删除了上述dd
命令结果中的换行符。 您将通过下面的测试代码看到它:
for (( i=1; i<=3; i++ )); do
c="$(dd if=test1 skip="$i" bs=1 count=1 2>/dev/null)"
echo "skip = $i"
echo -n "$c" | xxd
done
通常bash
不适合显式处理换行符,因为 bash 有时会自动删除或添加它。
如果perl
是您的选择,请尝试以下操作:
perl -0777 -ne '
$given = 3; # an example of the given offset
printf "character at offset %d = %s\n", $given, substr($_, $given, 1);
$pos = rindex(substr($_, 0, $given), "\n", $given);
if ($pos < 0) {
print "not found\n";
} else {
printf "newline found at offset %d\n", $given - $pos - 1;
}
' file
如果您更喜欢bash
,这里是 bash 中的替代方案:
file="./file"
given=3 # an example of the given offset
str="$(xxd -ps "$file" | tr -d '\n')" # to the hexadecimal expression
for (( i=given; i>=0; i-- )); do
j=$(( i * 2 ))
c="${str:$j:2}" # substring offset j, length 2
if [[ $c = "0a" ]]; then # search for the substring "0a"
printf "newline found at offset %d\n" $(( given - i - 1 ))
exit
fi
done
echo "not found"
概念与 perl 版本相同。 它首先将整个文件转换为十六进制表达式,然后从给定的 position 开始向后搜索 substring “0a”。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.