簡體   English   中英

如何確定 bash 中的換行符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM