0

I have a file that has error messages as per below

rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1505) 
rsync error: error in rsync protocol data stream (code 12) at token.c(604)

I want to extract the code number eg 23 in the first line and 12 in second.

  • Is this a file that contains tho output of multiple rsync runs? rsync usually uses these codes as exit status, so there's an opportunity to catch them directly from the utility when running it too, by investigating $?. – Kusalananda Dec 12 '18 at 6:49
  • Yes this file will contain output from many rsync runs. – Nem Dec 13 '18 at 23:10
  • If any of the answers solved your problem, please accept it by clicking the checkmark next to it. Thank you! – Jeff Schaller Jan 6 at 14:33
1

Like

$ grep -o "(code [0-9]*" file | cut -d" " -f2
23
12

?

  • Or, with GNU grep: grep -oP 'code \K\d+' or grep -oP '(?<=code )\d+' – glenn jackman Dec 12 '18 at 16:07
  • unfortunately this is a aix environment and does not support -o for grep and no equivalent flag. – Nem Dec 13 '18 at 23:08
  • @Nem sed -n 's/.*(code \([0-9]*\)).*/\1/p' your_file – mosvy Dec 13 '18 at 23:44
0

Using awk, you can extract the numbers in various ways. The script below expects to see a pattern of:

  1. a space
  2. (
  3. the string code
  4. a space
  5. a sequence of digits
  6. )
  7. a space

... which is not fool-proof, so I try to further limit the scope by restricting the matches to being on lines that start with the string rsync error:.

The remaining print code simply adjusts the string length parameters to account for the leading and trailing text.

awk '/^rsync error: .* \(code [[:digit:]]+\) / \
  { 
    match($0, " \\(code [[:digit:]]+\\) "); 
    print substr($0, RSTART + 7, RLENGTH - 9) ; 
  }' input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.