Find the answer to your Linux question:
Results 1 to 8 of 8
Hey ... I need to create a text processing script that can copy certain lines of a file and write it to a seperate file. So for example, copy lines ...
  1. #1
    Just Joined!
    Join Date
    Jun 2007
    Posts
    4

    Bash script - Text Processing

    Hey ...
    I need to create a text processing script that can copy certain lines of a file and write it to a seperate file. So for example, copy lines 40 through 50 or 100 through 200 (the lines to be copied would be different each time, specified by the users need).

    Please take a look at my comments below.

    Thanks !!

  2. #2
    Just Joined!
    Join Date
    Jun 2007
    Posts
    4
    To copy between two defined lines I came up with:

    Sed –n ‘(starting line),(ending line)p’ (input file) >> (output file)

    which does the job


    I tried creating a script:

    #!/bin/bash

    Sed –n ‘$1,$2p’ $3 >> $4

    Gives me an error:
    sed: -e expression #1, char 2: Unknown command: `1'

    When I run the script on the command line:
    i.e. ./script 8 10 input output

  3. #3
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    This would do the trick:

    Code:
    sed -n "$1,$2p" $3 >> $4
    The reason to use double quotes is to invoke the shell to expand the parameters.

    Regards

  4. #4
    Just Joined!
    Join Date
    Jun 2007
    Posts
    4
    I’m trying now to get the script to print between one line after the ones specified

    So if.

    ./script 8 10 input output

    It would write lines 9 – 11 instead of 8 – 10.

    I tried:



    #!/bin/bash

    # Same as command

    # invoked from the command line.



    sed -n "$1+1,$2+1p" "$3" > "$4"



    exit 0

  5. #5
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    Try the expr command, check the man page.

    Regards

  6. #6
    Just Joined!
    Join Date
    Jun 2007
    Posts
    4
    #!/bin/bash
    # Same as command
    # invoked from the command line.

    $1="expr $$1 + 1"
    $2="expr $$2 + 1"
    sed -n '1,1p' "$3" >> "$4"
    sed -n "$1,$2p" "$3" >> "$4"

    exit 0

    Get a lot of different errors while playing with variants. Any more suggestions?

  7. #7
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    This should work:

    Code:
    FROM=`expr $1 + 1`
    UNTIL=`expr $2 + 1`
    
    sed -n "$FROM,$UNTIL p" "$3" >> "$4"
    Have a read of some tutorials:

    http://www.tldp.org/LDP/Bash-Beginne...tml/index.html
    http://tldp.org/LDP/abs/html/

    Regards

  8. #8
    Linux User
    Join Date
    Aug 2006
    Posts
    458
    Code:
    printf "Enter start: "
    read start
    printf "Enter end: "
    read end
    awk -v start=$start -v end=$end 'NR>=start && NR<=end {print $0 }' "file" > output

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...