a.t.
a.t.

Reputation: 2779

Bash appends space at start of line when removing the first n lines of a txt file

Observed result

While writing a function that removes a variable nr of n lines from a file, the output file has an additional space at the first position of each line (after the first line).

For example:

some text
another text
third text
fourth text
fifth text

goes to:

third text
 fourth text
 fifth text

after removing the first n=2 lines.

Expected result

I would intend/expect those additional spaces not to be added, in essence:

third text
fourth text
fifth text

Code

The function that does the removal consists of:

#!/bin/bash
apt_update() {
    source src/hardcoded_variables.txt

    # copy target file
    cp $INPUT_PATH $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE

    # get starting line number
    starting_line=$(<$STARTING_LINE_QUERY_VAR_PATH)
    
    # remove first starting_line lines from the copied target file
    echo -n $(sed "1,${starting_line}d" $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE) > $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE
}
apt_update "$@"

Question

How could I prevent the adding of the space at the start of each line after the first line in the output file?

Upvotes: 0

Views: 84

Answers (1)

a.t.
a.t.

Reputation: 2779

The answer was given as a comment by Shawn, I used a convoluted method of sed that led to an error. Furthermore, I first made a copy of a file and that tried to apply sed to that same file. When I first made the copy, but then piped from the original file to the copied file, the target file was filled as expected. Hence, a working solution was found with:

#!/bin/bash
apt_update() {
    source src/hardcoded_variables.txt

    # copy target file
    cp $INPUT_PATH $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE

    # get starting line number
    starting_line=$(<$STARTING_LINE_QUERY_VAR_PATH)
    
    # remove first starting_line lines from the copied target file
    sed "1,${starting_line}d" $INPUT_PATH > $REMAINING_LINES_IN_TARGET_AFTER_STARTING_LINE
}
apt_update "$@"

I did need to make the target copy before applying sed in this solution.

Upvotes: 0

Related Questions