Replacing Control Character in sed

后端 未结 5 1977
再見小時候
再見小時候 2020-12-01 03:29

I need to replace all occurrences of the control character CTRL+A (SOH/ascii 1) in a text file in linux, how can this be achieved in SED?

相关标签:
5条回答
  • 2020-12-01 03:34

    You Can use tr command

    tr -s '\001' '|' newfile

    tr -s "word or delimiter" want to replace with "word or delimiter" newfile

    0 讨论(0)
  • 2020-12-01 03:41

    This can be done through cat with the -v (equivalently --show-nonprinting options and piping this into sed).

    If the control character the start of heading (SOH) character (CTRL+A / ASCII 1), and we want to replace it with a tab, we would do the following:

    cat -v file | sed 's/\^A/\t/g' > out
    

    cat -v would replace the SOH character with ^A, which would then be matched and replaced in sed.

    0 讨论(0)
  • 2020-12-01 03:49

    What do you want to replace them with? If the replacement is a single character, tr is a better choice than sed. To replace with the letter 'a':

    tr '\1' a < input-file > tmp && mv tmp input-file
    
    0 讨论(0)
  • 2020-12-01 03:55

    By "replace", I'm assuming you want to change the file 'in-place'.

    Using GNU sed:

    # Create a file with a single control character (SOH)
    echo -e "\x01" > file
    # Change SOH control characters to the literal string "SOH"
    sed -i 's/\x01/SOH/g' file
    # Check result
    cat file
    

    gives...

    SOH
    

    The -i option doesn't work on OS X sed, so you'd need to work-around that by piping sed to a temporary file.

    0 讨论(0)
  • 2020-12-01 03:58

    Try:

    sed 's/^A/foo/g' file
    

    Use Ctrl+V+A to create the ^A sequence in the above command.

    0 讨论(0)
提交回复
热议问题