[Solved] Shell script to read unhashed lines from file.
Hello.
I want to write a shell script (it can be bash,sh,ksh,csh or zsh) that will be:
1.Read unhashed lines from file named mirrors.conf.
2.Put them in ~/.profile as PKG_PATH=line catted from mirrors.conf.
Just like as mirrors.conf file for pacman.
Now it can cat lines but how to put them in files as PKG_PATH?
Thanks for answers.
Last edited by SpeedVin (2010-03-01 17:33:20)
res wrote:
^ IFS is not necessary here; it won't mess with the white space:
$ echo 'args with formatted spaces ' | while read -r; do echo "$REPLY"; done
args with formatted spaces
It matters for leading/trailing whitespace:
$ echo ' after some ' | while read -r line; do echo "<$line>"; done
<after some>
$ echo ' after some ' | while IFS= read -r line; do echo "<$line>"; done
< after some >
Similar Messages
-
Shell scripts to read data from a text file and to load it into a table
Hi All,
I have a text file consisting of rows and columns as follows,
GEF001 000093625 MKL002510 000001 000000 000000 000000 000000 000000 000001
GEF001 000093625 MKL003604 000001 000000 000000 000000 000000 000000 000001
GEF001 000093625 MKL005675 000001 000000 000000 000000 000000 000000 000001 My requirement is that, i should read the first 3 columns of this file using a shell script and then i have to insert the data into a table consisting of 3 rows in oracle .
the whole application is deployed in unix and that text file comes from mainframe. am working in the unix side of the application and i cant access the data directly from the mainframe. so am required to write a script which reads the data from text file which is placed in certain location and i have to load it to oracle database.
so I can't use SQL * loader.
Please help me something with this...
Thanks in advance.1. Create a dictionary object in Oracle and assign it to the folder where your file resides
2. Write a little procedure which opens the file in the newly created directory object using ULT_FILE and inside the FOR LOOP and do INSERTs to table you want
3. Create a shell script and call that procedure
You can use the post in my Blog for such issues
[Using Oracle UTL_FILE, UTL_SMTP packages and Linux Shell Scripting and Cron utility together|http://kamranagayev.wordpress.com/2009/02/23/using-oracle-utl_file-utl_smtp-packages-and-linux-shell-scripting-and-cron-utility-together-2/]
Kamran Agayev A. (10g OCP)
http://kamranagayev.wordpress.com -
How to read some lines from a text file using java.
hi,
i m new to java and i want to read some lines from a text file based on some string occurrence in the file. This file to be read in steps.
we only want to read the file upto the first Occurrence of "TEXT" string.
How to do it ,,,
Kinldy give the code
Regards,
Sagar
this is the text file
dfgjdjj
sfjhjkd
ghjkdg
hjkdgh TEXT
ikeyt
ujt
jk
tyk TEXT
rukl
rHendawy wrote:
Since the word "TEXT" is formed of 4 letters, you would read the text file 4 bytes by four bytes. Wrong on two counts. First, the file may not be encoded 1 byte per character. It could be utf-16 in which case it would be two byte per character. Second, even if it were 1 byte per character, the string "Text" may not start on a 4 byte boundary.
Consider a FileInputStream object "fis" that points to your text file. use fis.read(byte[] array, int offset, int len) to read every four bytes. Convert the "TEXT" String into a byte array "TEXT".getBytes(), and yous the Arrays class to compare the equality of the read bytes with your "TEXT".getBytes()Wrong since it relies on my second point and will fail when fis.read(byte[] array, int offset, int len) does not read 4 bytes (as is no guaranteed to). Check the Javadoc. Also, the file may not be encoded with the default character encoding.
The problem is easily solved by reading a line at a time using a BufferedReader wrapping an InputStreamReader wrapping a FileInputStream and specifying the correct character encoding.
Edited by: sabre150 on Apr 29, 2009 2:13 PM -
How do i read complete line from a text file in j2me?????
how do i read complete line from a text file in j2me????? I wanna read file line by line not char by char..Even i tried with readUTF of datainputstream to read word by word but i got UTFDataFormatException.. Please solve my problem.. Thanks in advance..
That is not my problem . i already read it char by char.. i am getting complete line..But this process is taking to much time..So thats why i directly wanna read complete line or word to save time..
-
I need a shell script to move latest archivelogs from one server to another server..
Hi,
I need a shell script to move latest archivelogs from one server to another server..
Thanks&Regards,
Velea816fb9-f9ea-45ac-906f-36a8315970d0 wrote:
Thanks it's really helpfull..
Now i have pasted a shell script which generates archivelog and shows latest archivelog time..
just check let me know the answer, that how i need to execute it..
# Force a logswitch to get the last archivelog to the standby host
ORACLE_SID=ORCL
ORAENV_ASK=NO
. oraenv >/dev/null 2>&1
SwitchLogfile()
# Do logswitch
RESULT=`echo "Alter system switch logfile;" | sqlplus -S / as sysdba | grep 'System altered'`
if [ "$RESULT" = "System altered." ]
then
export RETURN=1
else
export RETURN=0
fi
# Do we need to do something with this return value?
export RETURN
GetArchiveTime()
CURYEAR=`date +%Y`
echo "set heading off;" > temp.sql
echo "set termout off;" >> temp.sql
echo "select to_char(first_time,'YYYY-MM-DD HH24:MI:SS') from v\$archived_log where sequence#=(select sequence# - 1 from v\$log where status='CURRENT');" >> temp.sql
sqlplus -S / as sysdba <
spool tempres.txt
@temp.sql
quit
EOF
cat tempres.txt | grep ${CURYEAR} | grep -v grep | awk '{print $1" "$2}'
#rm -f temp.sql tempres.sql
SwitchLogfile
GetArchiveTime
You seem to have ignored Dude's VERY good advice and continue to press down this ill-advised path. If you continue this approach, you WILL have problems at the very time you do not need any additional problems. Trying to recover your production database at 2:00 in the morning is not the time to be getting errors from rman because it can't find what it needs - because you decided to move them around yourself.
Please reconsider. -
Reading one line from a text file into an array
i want to read one line from a text file into an array, and then the next line into a different array. both arays are type string...i have this:
public static void readAndProcessData(FileInputStream stream){
InputStreamReader iStrReader = new InputStreamReader (stream);
BufferedReader reader = new BufferedReader (iStrReader);
String line = "";
try{
int i = 0;
while (line != null){
names[i] = reader.readLine();
score[i] = reader.readLine();
line = reader.readLine();
i++;
}catch (IOException e){
System.out.println("Error in file access");
this section calls it:
try{
FileInputStream stream = new FileInputStream("ISU.txt");
HighScore.readAndProcessData(stream);
stream.close();
names = HighScore.getNames();
scores = HighScore.getScores();
}catch(IOException e){
System.out.println("Error in accessing file." + e.toString());
it gives me an array index out of bounds erroroh wait I see it when I looked at the original quote.
They array you made called names or the other one is prob too small for the amount of names that you have in the file. Hence as I increases it eventually goes out of bounds of the array so you should probably resize the array if that happens. -
How can I input read a line from a file and output it into the screen?
How can I input read a line from a file and output it into the screen?
If I have a file contains html code and I only want the URL, for example, www24.brinkster.com how can I read that into the buffer and write the output into the screen that using Java?
Any help will be appreciate!
======START FILE default.html ========
<html>
<body>
<br><br>
<center>
<font size=4 face=arial color=#336699>
<b>Welcome to a DerekTran's Website!</b><br>
Underconstructions.... <br>
</font> </center>
<font size=3 face=arial color=black> <br>
Hello,<br>
<br>
I've been using the PWS to run the website on NT workstation 4.0. It was working
fine. <br>
The URL should be as below: <br>
http://127.0.0.1/index.htm or http://localhost/index.htm
<p>And suddently, it stops working, it can't find the connection. I tried to figure
out what's going on, but still <font color="#FF0000">NO CLUES</font>. Does anyone
know what's going on? Please see the link for more.... I believe that I setup
everything correctly and the bugs still flying in the server.... <br>
Thank you for your help.</P>
</font>
<p><font size=3 face=arial color=black>PeerWebServer.doc
<br>
<p><font size=3 face=arial color=black>CannotFindServer.doc
<br>
<p><font size=3 face=arial color=black>HOSTS file is not found
<br>
<p><font size=3 face=arial color=black>LMHOSTS file
<br>
<p><font size=3 face=arial color=black>How to Setup PWS on NT
<BR>
<p><font size=3 face=arial color=black>Issdmin doc</BR>
Please be patient while the document is download....</font>
<font size=3 face=arial color=black><br>If you have any ideas please drop me a
few words at [email protected] </font><br>
<br>
<br>
</p>
<p><!--#include file="Hits.asp"--> </p>
</body>
</html>
========= END OF FILE ===============Hi!
This is a possible solution to your problem.
import java.io.*;
class AddressExtractor {
public static void main(String args[]) throws IOException{
//retrieve the commandline parameters
String fileName = "default.html";
if (args.length != 0) fileName =args[0];
else {
System.out.println("Usage : java AddressExtractor <htmlfile>");
System.exit(0);
BufferedReader in = new BufferedReader(new FileReader(new File(fileName)));
StreamTokenizer st = new StreamTokenizer(in);
st.lowerCaseMode(true);
st.wordChars('/','/'); //include '/' chars as part of token
st.wordChars(':',':'); //include ':' chars as part of token
st.quoteChar('\"'); //set the " quote char
int i;
while (st.ttype != StreamTokenizer.TT_EOF) {
i = st.nextToken();
if (st.ttype == StreamTokenizer.TT_WORD) {
if (st.sval.equals("href")) {
i = st.nextToken(); //the next token (assumed) is the '=' sign
i = st.nextToken(); //then after it is the href value.
getURL(st.sval); //retrieve address
in.close();
static void getURL(String s) {
//Check string if it has http:// and truncate if it does
if (s.indexOf("http://") > -1) {
s = s.substring(s.indexOf("http://") + 7, s.length());
//check if not mailto: do not print otherwise
if (s.indexOf("mailto:") != -1) return;
//printout anything after http:// and the next '/'
//if no '/' then print all
if (s.indexOf('/') > -1) {
System.out.println(s.substring(0, s.indexOf('/')));
} else System.out.println(s);
}Hope this helps. I used static methods instead of encapsulating everyting into a class. -
How to read every line from a text file???
How can i read every line from my text file ("eka.txt")
now it only reads the first line and prints it out.
What is wrong with this?
import java.io.*;
import java.util.*;
class Testi{
public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
File inputFile = new File ("eka.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);
String test=bis.readLine();
String tmp= "";
while((bis.readLine().trim() != null)) {
int spacefound=0;
int l=test.indexOf(" ");
for(int i=0;i<test.length();i++){
char c=test.charAt(i);
if(c!=' ') tmp+=""+c;
if(c==' ' && (spacefound<1) && !(tmp.equals(""))){
tmp+=""+c;
spacefound++;
if(tmp.length()==l) {
System.out.println(tmp);
tmp="";
spacefound=0;
if(tmp.length()<l){
for(int i=0;i<=(l-tmp.length());i++)
tmp+=""+' ';
System.out.println(tmp);Try this code, Hope it servers your purpose.
import java.io.*;
import java.util.*;
class Testi {
public static void main(String []args)throws IOException {
BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in));
File inputFile = new File ("Eka.txt");
FileReader fis =new FileReader(inputFile);
BufferedReader bis = new BufferedReader(fis);
String test=bis.readLine();
while(test != null) {
StringTokenizer st = new StringTokenizer(test," ");
while(st.hasMoreTokens())
System.out.println(st.nextToken());
test = bis.readLine();
}Sudha -
Having trouble reading specific lines from a text file and displaying them in a listbox
I am trying to read specific lines from all of the text files in a folder that are reports. When I run the application I get the information from the first text file and then it returns this error: "A first chance exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll"
Below is the code from that form.
Option Strict On
Option Infer Off
Option Explicit On
Public Class frmInventoryReport
Public Function ReadLine(ByVal lineNumber As Integer, ByVal lines As List(Of String)) As String
Dim intTemp As Integer
intTemp = lineNumber
Return lines(lineNumber - 1)
lineNumber = intTemp
End Function
Public Function FileMatches(ByVal folderPath As String, ByVal filePattern As String, ByVal phrase As String) As Boolean
For Each fileName As String In IO.Directory.GetFiles(folderPath, filePattern)
If fileName.ToLower().Contains(phrase.ToLower()) Then
Return True
End If
Next
Return False
End Function
Private Sub frmInventoryReport_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim intcase As Integer = 1
Dim strTemp, strlist, strFile As String
Dim blnCheck As Boolean = True
strFile = "Report Q" & intcase.ToString & ".txt"
Do While blnCheck = True
strFile = "Report Q" & intcase.ToString & ".txt"
Dim objReader As New System.IO.StreamReader("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\" & strFile)
Dim allLines As List(Of String) = New List(Of String)
Do While objReader.Peek <> -1
allLines.Add(objReader.ReadLine())
Loop
objReader.Close()
strlist = ReadLine(1, allLines) & "" & ReadLine(23, allLines)
lstInventory.Items.Add(strlist)
intcase += 1
strTemp = intcase.ToString
strFile = "Report Q" & intcase.ToString & ".txt"
blnCheck = FileMatches("E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\", "*.txt", intcase.ToString)
Loop
End Sub
End Class
Sorry I'm just beginning coding and I'm still a noob. Any help is appreciated. Thank you!Ok, so if I'm following this correctly you should be able to just loop through all of the files in that folder whose file name matches the pattern and then read the first 22 lines, recording only the first and the last.
Exactly how you store the animal data probably depends on how you are going to display it and what else you are going to do with it. Is there anything other than name and cage number that should be associated with each animal?
You might want to make a dataset with a datatable to describe the animal, or you might write a class, or you might just use something generic like a Tuple. Here's a simple class example:
Public Class Animal
Public Property Name As String
Public Property Cage As String
Public Overrides Function ToString() As String
Return String.Format("{0} - {1}", Name, Cage)
End Function
End Class
With that you can use a routine like the following to loop through all of the files and read each one:
Dim animals As New List(Of Animal)
Dim folderPath As String = "E:\Furry Friends Animal Shelter Solution\Furry Friends Animal Shelter\"
For Each filePath As String In System.IO.Directory.GetFiles(folderPath, "Report Q?.txt")
Using reader As New System.IO.StreamReader(filePath)
Dim lineIndex As Integer = 0
Dim currentAnimal As New Animal
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
If lineIndex = 0 Then
currentAnimal.Name = line
ElseIf lineIndex = 22 Then
currentAnimal.Cage = line
Exit While
End If
lineIndex += 1
End While
animals.Add(currentAnimal)
End Using
Next
'do something to display the animals list
Then you might bind the animals list to a ListBox, or loop through the list and populate a ListView. If you decided to fill a datatable instead of making Animal instances, then you might bind the resulting table to a DataGridView.
There are lots of options depending on what you want and what all you need to do.
Reed Kimble - "When you do things right, people won't be sure you've done anything at all" -
I want to read lines from file, count it and extract numbers from a first line.
i must do un loop?
HI,
i try to explain how to use to LABVIEW TOOLS...
1. USE a for next loop
2. here you must open the file with the VI. read lines from file.
you can choos how many lines you read at same time.
3. the string you can convert into an number.
4. in the loop is the literal counter... this is you line couter....
iun schrieb:
> i must do un loop? -
I can't read a Object from file, Please help me
i want to write a Object into File. this is code of Object
class objStoreCus implements Comparable, Serializable
String customerID = new String();
String customerName = new String();
String customerEmail = new String();
objStoreCus(String cusID, String cusName, String cusEmail)
customerID = cusID;
customerName = cusName;
customerEmail = cusEmail;
objStoreCus(){}
public int compareTo(Object o)
objStoreCus oS = new objStoreCus();
oS = (objStoreCus)o;
return(customerEmail.compareTo(oS.customerEmail));
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
try
s.defaultReadObject();
}catch(IOException ie){throw new IOException();}
catch(ClassNotFoundException cnt){throw new ClassNotFoundException();}
And I was wrote above Object into File by this code :+
FileOutputStream fos;
ObjectOutputStream oos;
FileInputStream fis;
ObjectInputStream ois;
public void writeObjToFile(objStoreCus obj)
try
fos = new FileOutputStream("Exrcise3.ex3", true);
}catch(FileNotFoundException fnfe){}
try
oos = new ObjectOutputStream(fos);
//ghi doi tuong vao file
oos.writeObject(obj);
//dong stream
oos.close();
fos.close();
}catch(IOException ie){}
But i can't read above Object from file. allway have a Exception occur "StreamCorruptedException".
this is code read Object form file :
*parameter is ArrayList will be store Object from file.
public void readObjFromFile(ArrayList al)
try
fis = new FileInputStream("Exrcise3.ex3");
}catch(FileNotFoundException fnfe){}
try
ois = new ObjectInputStream(fis);
while(true)
try
objStoreCus osc = new objStoreCus();
osc = (objStoreCus)ois.readObject();
System.out.println(osc.customerEmail);
}catch(Exception e)
e.printStackTrace();
//System.out.println();
break;
ois.close();
fis.close();
}catch(IOException ie){}
}Problem lies in
os = new FileOutputStream("Exrcise3.ex3", true);
You are trying to append to that file, You should always use new file to serialize objects.
os = new FileOutputStream("Exrcise3.ex3");
Try with above line. -
Read image direct from file server
hello, need to help me somebody.
A like to create form , what read image direct from file server, without store in database.
Please help me.Hi you may go through the below post to find what could be a better way to do that.
http://forum.java.sun.com/thread.jspa?threadID=5163829
REGARDS,
RaHuL -
Need help with EXS24 "read velocity range from file name"
I am trying to import 127 drum samples to a single key using the option shown here. The option says "Map to key dropped on and read velocity range from file name". I can find no documentation in the manuals on how to do this. What is the syntax required in the file name to make this work? I need to do several of these imports. The capability is cleary there, but I need help on how the file name should be formatted. My thanks to anyone who can help.
Hi
Not a direct answer to your question, but if you are doing a lot of sample mapping etc, you may want to check out Redmatica's KeyMap Pro or the simpler Keymap 1:
http://www.redmatica.com
CCT -
EXS24 read root key from file name only
Has anyone encountered this with EXS24 in Logic 7? If you set preferences to "read root key from file name only" then EXS reads the root key from the file itself when loading samples. On the other hand if you set them to "read root key from file only" then it reads the root key from the file name. Or am I just imagining this?
P.S. if anyone from Apple is reading, could you please update EXS24? It's a bit primitive by today's standards.Hi
Not a direct answer to your question, but if you are doing a lot of sample mapping etc, you may want to check out Redmatica's KeyMap Pro or the simpler Keymap 1:
http://www.redmatica.com
CCT -
How to read appended objects from file with ObjectInputStream?
Hi to everyone. I'm new to Java so my question may look really stupid to most of you but I couldn't fined a solution by myself... I wanted to make an application, something like address book that is storing information about different people. So I decided to make a class that will hold the information for each person (for example: nickname, name, e-mail, web address and so on), then using the ObjectOutputStream the information will be save to a file. If I want to add a new record for a new person I'll simply append it to the already existing file. So far so good but soon I discovered that I can not read the appended objects using ObjectInputStream.
What I mean is that if I create new file and then in one session save several objects to it using ObjectOutputStream they all will be read with no problem by ObjectInputStream. But after that if in a new session I append new objects they won't be read. The ObjectInputStream will read the objects from the first session after that IOException will be generated and the reading will stop just before the appended objects from the second session.
The following is just a simple test it's not actual code from the program I was talking about. Instead of objects containing different kind of information I'm using only strings here. To use the program use as arguments in the console "w" to create new file followed by the file name and the strings you want save to the file (as objects). Example: "+w TestFile.obj Thats Just A Test+". Then to read it use "r" (for reading), followed by the file name. Example "+r TestFile.obj+". As a result you'll see that all the strings that are saved in the file can be successfully read back. Then do the same: "+w TestFile.obj Thats Second Test+" and then read again "+r TestFile.obj+". What will happen is that the strings only from the first sessions will be read and the ones from the second session will not.
I am sorry for making this that long but I couldn't explain it more simple. If someone can give me a solution I'll be happy to hear it! ^.^ I'll also be glad if someone propose different approach of the problem! Here is the code:
import java.io.*;
class Fio
public static void main(String[] args)
try
if (args[0].equals("w"))
FileOutputStream fos = new FileOutputStream(args[1], true);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (int i = 2; i < args.length ; i++)
oos.writeObject(args);
fos.close();
else if (args[0].equals("r"))
FileInputStream fis = new FileInputStream(args[1]);
ObjectInputStream ois = new ObjectInputStream(fis);
for (int i = 0; i < fis.available(); i++)
System.out.println((String)ois.readObject());
fis.close();
else
System.out.println("Wrong args!");
catch (IndexOutOfBoundsException exc)
System.out.println("You must use \"w\" or \"r\" followed by the file name as args!");
catch (IOException exc)
System.out.println("I/O exception appeard!");
catch (ClassNotFoundException exc)
System.out.println("Can not find the needed class");How to read appended objects from file with ObjectInputStream? The short answer is you can't.
The long answer is you can if you put some work into it. The general outline would be to create a file with a format that will allow the storage of multiple streams within it. If you use a RandomAccessFile, you can create a header containing the length. If you use streams, you'll have to use a block protocol. The reason for this is that I don't think ObjectInputStream is guaranteed to read the same number of bytes ObjectOutputStream writes to it (e.g., it could skip ending padding or such).
Next, you'll need to create an object that can return more InputStream objects, one per stream written to the file.
Not trivial, but that's how you'd do it.
Maybe you are looking for
-
Purchase Price of Configured Product (KMAT)
We have a commodity which we will buying as a configured product. The commodity will contain several subassemblies which the supplier will put together and ship to us as a complete unit. I understand how to set up the materials in Variant Configurati
-
Business Partner Creation/Display - General Data fields are missing
Hi, We have an issue in our ECC6.0 system. In FPP1/FPP2/FPP3 transactions General data fields such as Driver's license, SSN, Employee class are missing under Identification tab. But the same are displayed in BP transaction code. What configuration wo
-
Photostream - error occurred while joining the Photo Stream
I have read/tried out the suggestions from other users with the same issue but I am unable to resolve my issue. I originally was able to join the Photostream on all my devices. On the Mac, suddenly I was no longer connected to iCloud. I eventually ma
-
I can not change color of mask for exemple: I make two solid(black and white) and i masking the white solid, then i going to color correction-color balance and change the color but i have not changed the color of the mask. Does it program mistake or
-
Exporting from FCP to Adobe Premier
hi gang, so, would like to export my short film (20 min) that I've finished editing in FCP 5.1.3 but I'm seeing something strange with the final product. It's seems really fuzzy/grainy when doing playback on a PC. I think that I might be doing someth