extract/delete line from file to other.
hi, guys
I need your help on a piece of code. i have 2 files. file1.txt with content: song1 song2 song3 song4 and an empty file2.txt and i want to extract and delete randomly a line from file1.txt and put it on file2.txt the result would be: file1.txt with content: song1 song2 song4 file2.txt with content: song3 |
Hi and Welcome to LQ.
Ok, where exactly are you stuck? |
I'm stuck with the command sed can't make it working :(
|
So what sed have you tried? Are you able to do the 2 individual tasks? ie print line to other file and delete line from first file.
|
Quote:
|
i don't have it yet, i know that sed can't remove line with an expression sed '/Hello/d' file.txt but i can't implement on the way to get a random line and put it on the other file!
|
i'm stuck in this, with this sed line i can get a random line and print on file2.txt but i can't insert this as variable on sed to delete the line.
GETLINE=$(sed -n $((1+$RANDOM%`wc -l file1.txt | cut -f 1 -d ' '`))p file1.txt > file2.txt) sed -e "/$GETLINE/d" file1.txt > file1_.txt mv file1_.txt file1.txt this is to run every 30 minutes and when file1.txt gets empty do: find /home/mp3/ -type f -name "*.mp3" > file1.txt |
It might be better to calculate a random line number (within range), and then use:
sed -n "${num}p" text1 >> text2 sed -i "${num}d" text1 You don't use slashes around the line number for one thing. Break up the problem so that your calculations is outside the sed command. declare -i lines random_line lines=$(($(wc -l text1))) random_line=$((${RANDOM}%${lines}+1)) There will be an error here. Declaring lines, and random_lines helped pick up the mistake. .. declare -i lines random_line lines=$(($(wc -l text1.txt | cut -d' ' -f1))) random_line=$(( ${RANDOM%${lines}+1 )) That's better. sed -n "${random_line}p" file1.txt >> file2.txt sed -i "${random_line}d" file1.txt A common catch is to not use $(( ... )) when dealing with integers. |
jschiwal impossible to do that because the total of number of lines it's not always equal. but thanks anyway, your code gave me a better ideia.
i found the solution: N=$((1+$RANDOM%`wc -l file1.txt | cut -f 1 -d ' '`)) sed -n "${N}p" file1.txt >> file2.txt sed -i "${N}d" file1.txt now i only got to implement an if statement when file1.txt gets empty. |
I thought you might like this tidy up:
Code:
(( N = 1 + RANDOM % $(cat file1.txt | wc -l) )) |
grail: don't you have to put the cut -f 1 -d ' ' part to remove the empty line on the file????
|
No you are using the cut because if you do:
Code:
wc -l file1.txt Code:
10 file1.txt Code:
cat file1.txt | wc -l |
ok got it!
SOLVED!!!!!!!!!!!!!!!! |
Cool ... look under thread tools to mark as SOLVED.
|
Quote:
My main point is that separating the tasks into separate lines can make debugging easier. Also use "declare -i" for integer variables to expose hidden errors where a string would be assigned to the variable. |
All times are GMT -5. The time now is 10:45 PM. |